<template>
  <div class="withdrawals-page">
    <h1 class="page-title">佣金提现</h1>

    <!-- 提现概览卡片 -->
    <div class="overview-cards">
      <div class="overview-card">
        <div class="overview-icon green">
          <i class="fas fa-wallet"></i>
        </div>
        <div class="overview-content">
          <div class="overview-title">可提现金额</div>
          <div class="overview-value">¥{{ formatNumber(withdrawalData.availableAmount) }}</div>
          <div class="overview-desc">满100元可提现</div>
        </div>
      </div>

      <div class="overview-card">
        <div class="overview-icon blue">
          <i class="fas fa-hourglass-half"></i>
        </div>
        <div class="overview-content">
          <div class="overview-title">提现中金额</div>
          <div class="overview-value">¥{{ formatNumber(withdrawalData.pendingAmount) }}</div>
          <div class="overview-desc">审核中的提现申请</div>
        </div>
      </div>

      <div class="overview-card">
        <div class="overview-icon purple">
          <i class="fas fa-check-circle"></i>
        </div>
        <div class="overview-content">
          <div class="overview-title">已提现总额</div>
          <div class="overview-value">¥{{ formatNumber(withdrawalData.totalWithdrawn) }}</div>
          <div class="overview-desc">累计已提现金额</div>
        </div>
      </div>

      <div class="overview-card">
        <div class="overview-content centered">
          <van-button type="primary" size="large" @click="showWithdrawalForm = true" class="withdraw-button">
            <i class="fas fa-money-bill-wave"></i> 申请提现
          </van-button>
        </div>
      </div>
    </div>

    <!-- 提现记录表格 -->
    <div class="withdrawals-table">
      <div class="table-header">
        <h2 class="section-title">提现记录</h2>
        <div class="filter-actions">
          <van-dropdown-menu>
            <van-dropdown-item v-model="filterStatus" :options="statusOptions" />
          </van-dropdown-menu>
          <div class="date-range">
            <input type="date" v-model="filterStartDate" class="date-input" />
            <span class="date-separator">至</span>
            <input type="date" v-model="filterEndDate" class="date-input" />
            <van-button size="small" type="primary" @click="applyFilters">筛选</van-button>
          </div>
        </div>
      </div>

      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th>申请ID</th>
              <th>申请时间</th>
              <th>提现金额</th>
              <th>收款方式</th>
              <th>状态</th>
              <th>审核时间</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in withdrawalRecords" :key="item.id">
              <td>{{ item.id }}</td>
              <td>{{ formatDate(item.applyTime) }}</td>
              <td class="amount">¥{{ formatNumber(item.amount) }}</td>
              <td>{{ item.method }}</td>
              <td>
                <span class="status-badge" :class="getStatusClass(item.status)">
                  {{ getStatusText(item.status) }}
                </span>
              </td>
              <td>{{ item.reviewTime ? formatDate(item.reviewTime) : '-' }}</td>
              <td>{{ item.remark || '-' }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <a href="#" class="page-link" @click.prevent="changePage(currentPage - 1)"
          :class="{ disabled: currentPage === 1 }">&laquo;</a>
        <template v-for="n in totalPages" :key="n">
          <a href="#" class="page-link" :class="{ active: currentPage === n }" @click.prevent="changePage(n)">
            {{ n }}
          </a>
        </template>
        <a href="#" class="page-link" @click.prevent="changePage(currentPage + 1)"
          :class="{ disabled: currentPage === totalPages }">&raquo;</a>
      </div>
    </div>

    <!-- 提现申请表单弹窗 -->
    <van-popup v-model:show="showWithdrawalForm" position="bottom" :style="{ height: '70%' }" round>
      <div class="withdrawal-form">
        <div class="form-header">
          <h2>申请提现</h2>
          <van-icon name="cross" @click="showWithdrawalForm = false" />
        </div>

        <van-form @submit="onSubmitWithdrawal">
          <van-cell-group inset>
            <van-field v-model="withdrawalForm.amount" type="number" name="amount" label="提现金额" placeholder="请输入提现金额"
              :rules="[
                { required: true, message: '请输入提现金额' },
                { validator: validateAmount, message: '提现金额必须在100-' + withdrawalData.availableAmount + '元之间' }
              ]">
              <template #right-icon>
                <span class="field-helper">可提现: ¥{{ formatNumber(withdrawalData.availableAmount) }}</span>
              </template>
            </van-field>

            <van-field v-model="withdrawalForm.usdtAddress" name="usdtAddress" label="USDT地址" placeholder="请输入您的USDT地址"
              :rules="[{ required: true, message: 'USDT地址不能为空' }]" />

            <van-field v-model="withdrawalForm.remark" name="remark" label="备注信息" type="textarea" placeholder="可选填写备注信息"
              rows="2" maxlength="100" show-word-limit />
          </van-cell-group>

          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit" :disabled="isSubmitting">
              <template v-if="!isSubmitting">提交申请</template>
              <template v-else>提交中...</template>
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { showToast, showSuccessToast } from 'vant'

// 提现数据
const withdrawalData = reactive({
  availableAmount: 6850.25,
  pendingAmount: 1200.00,
  totalWithdrawn: 15680.50,
})

// 表单显示状态
const showWithdrawalForm = ref(false)
const isSubmitting = ref(false)

// 提现表单数据
const withdrawalForm = reactive({
  amount: '',
  usdtAddress: '',
  remark: '',
})

// 表格筛选状态
const filterStatus = ref('all')
const filterStartDate = ref('')
const filterEndDate = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 状态选项
const statusOptions = [
  { text: '全部状态', value: 'all' },
  { text: '待审核', value: 'pending' },
  { text: '已通过', value: 'approved' },
  { text: '已拒绝', value: 'rejected' },
  { text: '已打款', value: 'paid' },
]

// 模拟提现记录数据
const allWithdrawalRecords = ref([
  {
    id: 'WD20230601001',
    applyTime: '2023-06-01 14:30:25',
    amount: 1000.00,
    method: 'USDT',
    status: 'paid',
    reviewTime: '2023-06-02 10:15:30',
    remark: '月度提现'
  },
  {
    id: 'WD20230615002',
    applyTime: '2023-06-15 09:22:18',
    amount: 2500.00,
    method: 'USDT',
    status: 'paid',
    reviewTime: '2023-06-16 11:05:42',
    remark: ''
  },
  {
    id: 'WD20230702003',
    applyTime: '2023-07-02 16:45:33',
    amount: 1800.00,
    method: 'USDT',
    status: 'approved',
    reviewTime: '2023-07-03 14:20:15',
    remark: '周佣金提现'
  },
  {
    id: 'WD20230720004',
    applyTime: '2023-07-20 10:12:50',
    amount: 3200.00,
    method: 'USDT',
    status: 'pending',
    reviewTime: null,
    remark: ''
  },
  {
    id: 'WD20230805005',
    applyTime: '2023-08-05 11:30:22',
    amount: 1500.00,
    method: 'USDT',
    status: 'rejected',
    reviewTime: '2023-08-06 09:45:10',
    remark: 'USDT地址格式错误'
  },
  {
    id: 'WD20230818006',
    applyTime: '2023-08-18 15:10:05',
    amount: 2000.00,
    method: 'USDT',
    status: 'pending',
    reviewTime: null,
    remark: ''
  },
  {
    id: 'WD20230901007',
    applyTime: '2023-09-01 09:05:18',
    amount: 3500.00,
    method: 'USDT',
    status: 'approved',
    reviewTime: '2023-09-02 10:30:22',
    remark: ''
  },
  {
    id: 'WD20230915008',
    applyTime: '2023-09-15 14:22:30',
    amount: 1200.00,
    method: 'USDT',
    status: 'paid',
    reviewTime: '2023-09-16 11:15:40',
    remark: '佣金提现'
  }
])

// 根据筛选条件计算显示的记录
const filteredRecords = computed(() => {
  let result = [...allWithdrawalRecords.value]

  // 应用状态筛选
  if (filterStatus.value !== 'all') {
    result = result.filter(record => record.status === filterStatus.value)
  }

  // 应用日期筛选
  if (filterStartDate.value) {
    const startDate = new Date(filterStartDate.value)
    result = result.filter(record => new Date(record.applyTime) >= startDate)
  }

  if (filterEndDate.value) {
    const endDate = new Date(filterEndDate.value)
    endDate.setHours(23, 59, 59, 999) // 设置为当天的最后一刻
    result = result.filter(record => new Date(record.applyTime) <= endDate)
  }

  return result
})

// 计算分页后的记录
const withdrawalRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredRecords.value.slice(start, start + pageSize.value)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.max(1, Math.ceil(filteredRecords.value.length / pageSize.value))
})

// 格式化金额，保留两位小数并添加千位分隔符
const formatNumber = (num: number): string => {
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
}

// 补零函数
const padZero = (num: number): string => {
  return num < 10 ? `0${num}` : num.toString()
}

// 获取状态对应的样式类
const getStatusClass = (status: string): string => {
  switch (status) {
    case 'pending': return 'status-pending'
    case 'approved': return 'status-approved'
    case 'rejected': return 'status-rejected'
    case 'paid': return 'status-paid'
    default: return ''
  }
}

// 获取状态对应的文本
const getStatusText = (status: string): string => {
  switch (status) {
    case 'pending': return '待审核'
    case 'approved': return '已通过'
    case 'rejected': return '已拒绝'
    case 'paid': return '已打款'
    default: return status
  }
}

// 切换页码
const changePage = (page: number) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
}

// 应用筛选条件
const applyFilters = () => {
  currentPage.value = 1 // 重置为第一页
}

// 验证提现金额
const validateAmount = (value: string) => {
  const amount = parseFloat(value)
  return amount >= 100 && amount <= withdrawalData.availableAmount
}

// 提交提现申请
const onSubmitWithdrawal = () => {
  isSubmitting.value = true

  // 模拟API请求
  setTimeout(() => {
    // 生成新的提现记录
    const newRecord = {
      id: `WD${new Date().getTime().toString().slice(-8)}`,
      applyTime: new Date().toISOString(),
      amount: parseFloat(withdrawalForm.amount),
      method: 'USDT',
      status: 'pending',
      reviewTime: null,
      remark: withdrawalForm.remark || ''
    }

    // 添加到记录列表
    allWithdrawalRecords.value.unshift(newRecord)

    // 更新可提现金额和提现中金额
    const amount = parseFloat(withdrawalForm.amount)
    withdrawalData.availableAmount -= amount
    withdrawalData.pendingAmount += amount

    // 重置表单
    withdrawalForm.amount = ''
    withdrawalForm.remark = ''

    // 关闭弹窗并显示成功提示
    showWithdrawalForm.value = false
    isSubmitting.value = false
    showSuccessToast('提现申请已提交，等待审核')
  }, 1000)
}

onMounted(() => {
  // 这里可以添加初始化逻辑，如从API获取数据等
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';

.withdrawals-page {
  padding: 20px;
}

.page-title {
  margin-top: 0;
  margin-bottom: 24px;
  color: $text-primary;
  font-size: 24px;
  font-weight: $font-weight-semibold;
  position: relative;

  &:after {
    content: '';
    position: absolute;
    left: 0;
    bottom: -8px;
    width: 40px;
    height: 3px;
    background: linear-gradient(90deg, $primary, $primary-light);
    border-radius: 3px;
  }
}

.section-title {
  font-size: $font-size-lg;
  margin: 0;
  color: $text-primary;
  font-weight: $font-weight-semibold;
}

// 提现概览卡片
.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.overview-card {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: $shadow-sm;
  transition: transform 0.2s, box-shadow 0.2s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: $shadow-md;
  }

  .overview-content.centered {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
  }
}

.overview-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;

  &.green {
    background-color: $success;
  }

  &.blue {
    background-color: $info;
  }

  &.purple {
    background-color: #8b5cf6;
  }
}

.overview-content {
  flex: 1;
}

.overview-title {
  font-size: 14px;
  color: $text-secondary;
  margin-bottom: 8px;
}

.overview-value {
  font-size: 24px;
  font-weight: $font-weight-semibold;
  color: $text-primary;
  margin-bottom: 5px;
}

.overview-desc {
  font-size: 13px;
  color: $text-secondary;
}

.withdraw-button {
  width: 100%;
  height: 44px;

  i {
    margin-right: 8px;
  }
}

// 提现记录表格
.withdrawals-table {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: $shadow-sm;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.date-range {
  display: flex;
  align-items: center;
}

.date-input {
  padding: 8px;
  border: 1px solid $gray-300;
  border-radius: 4px;
  width: 130px;
}

.date-separator {
  margin: 0 8px;
  color: $text-secondary;
}

.table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid $gray-200;
}

th {
  font-weight: $font-weight-medium;
  color: $text-secondary;
  background-color: $gray-100;
}

td {
  color: $text-primary;
}

td.amount {
  font-weight: $font-weight-medium;
  color: $primary;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: $font-weight-medium;
}

.status-pending {
  background-color: #e0e7ff;
  color: #1e40af;
}

.status-approved {
  background-color: #dcfce7;
  color: #166534;
}

.status-rejected {
  background-color: #fee2e2;
  color: #b91c1c;
}

.status-paid {
  background-color: #d1fae5;
  color: #047857;
}

// 分页
.pagination {
  display: flex;
  justify-content: center;
  gap: 5px;
  margin-top: 20px;
}

.page-link {
  display: inline-block;
  padding: 6px 12px;
  background-color: white;
  border: 1px solid $gray-300;
  color: $text-primary;
  text-decoration: none;
  border-radius: 4px;
  transition: all 0.2s;

  &:hover:not(.disabled, .active) {
    border-color: $primary;
    color: $primary;
  }

  &.active {
    background-color: $primary;
    color: white;
    border-color: $primary;
  }

  &.disabled {
    color: $gray-400;
    cursor: not-allowed;
  }
}

// 提现申请表单弹窗
.withdrawal-form {
  padding: 16px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 8px;

  h2 {
    font-size: 18px;
    margin: 0;
    color: $text-primary;
  }

  .van-icon {
    font-size: 20px;
    cursor: pointer;
    color: $text-secondary;

    &:hover {
      color: $primary;
    }
  }
}

.field-helper {
  font-size: 12px;
  color: $success;
}
</style>
